package Controller;

import java.sql.SQLException;
import java.util.Random;

import javax.mail.MessagingException;


import org.zkoss.web.servlet.dsp.action.Remove;
import org.zkoss.zk.ui.Executions;
import org.zkoss.zk.ui.Session;
import org.zkoss.zk.ui.Sessions;
import org.zkoss.zk.ui.WrongValueException;
import org.zkoss.zk.ui.select.SelectorComposer;
import org.zkoss.zk.ui.select.annotation.Listen;
import org.zkoss.zk.ui.select.annotation.Wire;
import org.zkoss.zul.Div;
import org.zkoss.zul.Label;
import org.zkoss.zul.Textbox;

import Misc.Functions;
import Misc.SendMail;


import databaseHelper.UserDAO;
import datatypes.User;
/**
 * 
 * registration controller. Handling the registration of an user.
 * 
 * generates password and sends it to user in email
 * 
 * @author Rupert
 *
 */
public class RegistrationController extends SelectorComposer<Div> {
	
	private UserDAO userDAO;
	
	@Wire
	private Textbox emailTxb;
	
	@Wire
	private Label validLogin;
	
	@Listen("onClick=#registerEmailButton")
	public void confirm(){
		doRegister();
	}

	@Listen("onClick=#backToLoginButton")
	public void backToLogin(){
		Executions.sendRedirect("login.zul");
	}

	
	boolean doRegister(){
		userDAO = new UserDAO();
		
		String allowedChars = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
		
		
		String randomPassword = Functions.generateRandomString(allowedChars);
		
		System.out.println("Random Password: "+ randomPassword);
		
		User createUser = new User(emailTxb.getValue(),randomPassword);
		
		boolean correctInsert = userDAO.insert(createUser);
		
		
		if(correctInsert){
			validLogin.setStyle("color: green; float:left;");
			validLogin.setValue("A email containing the password is send to your address!"); 
			
			try {
				sendEmailToUser( createUser.getName(), "Hi "+createUser.getName()+", \n" +
								" Log in @ http://http://vmbaumgarten2.informatik.tu-muenchen.de/ExamOnlineApp/ \n" +
								" Your password is: "+createUser.getPassword());
			} catch (MessagingException e) {
				// TODO Auto-generated catch block
				System.out.println("Sending failed!");
				e.printStackTrace();
				validLogin.setStyle("color: red; float:left;");
				validLogin.setValue("Sending email failed! Try register later."); 

				userDAO.remove(createUser);
				
				correctInsert = false;
			}
			
		}else{
			validLogin.setStyle("color: red; float:left;");
			validLogin.setValue("Insert failed! Maybe you already registered with this email address?"); 
			
		}
		if(correctInsert){
			Executions.sendRedirect("login.zul");
		}
		return correctInsert;
	}
	
	public static void sendEmailToUser(String receiver, String toMail) throws MessagingException {    
        String to = receiver;
        String subject = "ExamOnlineApp";
        String message = toMail;
 
        SendMail sendMail = new SendMail( to, subject, message);
        sendMail.send();
    }
	
	public void doAfterCompose(Div comp) throws Exception{
		super.doAfterCompose(comp);
		
		Session session = Executions.getCurrent().getSession();	
		if(UserCredentialManager.getInstance(session).isAuthenticated()){
			System.out.println("SCHON EINGELOGGT!");
			Executions.sendRedirect("dashboard.zul");
		}
	}

}
